
package hk.ces.oxfam.patch.connection;

import hk.ces.oxfam.patch.sql.PreparedSQL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;

/**
 *
 * @author ReutyCheng
 */
public class StatementFactory
{
  private StatementFactory()
  {
  }

  public static PreparedStatement getPrepareStatement(Connection connection, String sql) throws SQLException
  {
    PreparedStatement statement = connection.prepareStatement(sql);
    return statement;
  }

  public static PreparedStatement getPrepareStatement(Connection connection, PreparedSQL preparedSQL) throws SQLException
  {
    PreparedStatement statement = connection.prepareStatement(preparedSQL.getSql());
    return setParameters(statement, preparedSQL.getParams());
  }

  public static void closeResource(ResultSet resultSet)
  {
    closeResource(null, resultSet);
  }


  public static void closeResource(Statement statement)
  {
    closeResource(statement, null);
  }

  public static void closeResource(Statement statement, ResultSet resultSet)
  {
    try
    {
      if (statement != null)
      {
        statement.close();
      }
    }
    catch (SQLException ex)
    {
      Logger.getLogger(ConnectionUtil.class.getName()).error(ex.getMessage(), ex);
    }
    
    try
    {
      if (resultSet != null)
      {
        resultSet.close();
      }
    }
    catch (SQLException ex)
    {
      Logger.getLogger(ConnectionUtil.class.getName()).error(ex.getMessage(), ex);
    }
  }

  public static PreparedStatement setParameters(PreparedStatement statement, Object[] objects) throws SQLException
  {
    for (int index = 1; index < objects.length + 1; index++)
    {
      statement = setParameter(statement, index, objects[index - 1]);
    }

    return statement;
  }

  private static PreparedStatement setParameter(PreparedStatement statement, int paramIndex, Object object) throws SQLException
  {
    statement.setObject(paramIndex, object);
    return statement;
  }
}
